package com.example.springbootdemo.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * @Author: ShengXiaJia
 * @Date: 2019/12/6 15:27
 * @Description: 自定义过滤器例子
 */
@WebFilter(urlPatterns = "/api/*", filterName = "myFilter")
public class MyFilter implements Filter {

    /**
     * 容器加载的时候调用
     */
    @Override
    public void init(FilterConfig filterConfig) {
        System.out.println("========过滤器 init========");
    }

    /**
     * 请求被拦截的时候进行调用
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("========过滤器 doFilter========");
        filterChain.doFilter(servletRequest, servletResponse);
//        HttpServletRequest req = (HttpServletRequest) servletRequest;
//        HttpServletResponse rep = (HttpServletResponse) servletResponse;
//        String username = req.getParameter("username");
//        if ("class".equals(username)) {
//            filterChain.doFilter(servletRequest, servletResponse);
//        } else {
//            rep.sendRedirect("/index.ftl");
//            return;
//        }
    }

    /**
     * 容器被销毁的时候被调用
     */
    @Override
    public void destroy() {
        System.out.println("========过滤器 destroy========");
    }

}
